package com.cgsd.heyu.http.interceptor;

import com.android.library.utils.StringUtils;
import com.cgsd.heyu.common.Helper;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.TreeMap;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;

/**
 * @author xiaoxing
 * 添加公共header参数
 */
public class HeaderInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request originalRequest = chain.request();
        Request.Builder builder = originalRequest.newBuilder();
        TreeMap<String, String> treeMap = getCommonHeader();
        for (Map.Entry<String, String> stringStringEntry : treeMap.entrySet()) {
            String key = stringStringEntry.getKey();
            String value = stringStringEntry.getValue();
            if (StringUtils.isNotEmpty(value)) {
                builder.addHeader(key, value);
            }
        }
        if ("POST".equals(originalRequest.method())) {
            String url = originalRequest.url().url().getPath();
            if (originalRequest.body() instanceof RequestBody) {
                RequestBody formBody = originalRequest.body();
                Buffer buffer = new Buffer();
                formBody.writeTo(buffer);
                Charset charset = Charset.forName("UTF-8");
                MediaType contentType = formBody.contentType();
                if (contentType != null) {
                    charset = contentType.charset();
                }
                String paramsStr = buffer.readString(charset);
                if (StringUtils.isEmpty(paramsStr)) {
                    RequestBody requestBody = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), "{}");
                    originalRequest = originalRequest.newBuilder().post(requestBody).build();
                }
            }
        }
        Request.Builder requestBuilder = builder.method(originalRequest.method(), originalRequest.body());
        Request request = requestBuilder.build();
        return chain.proceed(request);
    }

    /**
     * 统header参数添加
     *
     * @return
     */
    private TreeMap<String, String> getCommonHeader() {
        TreeMap<String, String> treeMap = new TreeMap<>();
        treeMap.put("userChannel", "2");
        //token上传
        String accessToken = Helper.getTokenInfo();
        String token = Helper.getTokenPhpInfo();
        if (StringUtils.isNotEmpty(accessToken)) {
            treeMap.put("accessToken", accessToken);
        }
        if (StringUtils.isNotEmpty(token)) {
            treeMap.put("token", token);
        }
        return treeMap;
    }

}
